#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   init.py
@Time    :   2021/02/05 21:26:59
@Author  :   superjin
@Version :   1.0
'''

from fastapi import FastAPI,Request,Response
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware import Middleware
from router.v1_router import api_v1_router
from setting.config import settings
from fastapi.staticfiles import StaticFiles



def create_app()->FastAPI:
    app = FastAPI(
        debug=settings.DEBUG,
        title=settings.TITLE,
        description=settings.DESCRIPTION,
        docs_url=settings.DOCS_URL,
        openapi_url=settings.OPENAPI_URL,
        redoc_url=settings.REDOC_URL,
        version=settings.VERSION
    )
    app.mount("/statics", StaticFiles(directory="statics"), name="statics")
    #允许跨域
    register_cors(app)

    #注册路由
    register_router(app)

    #注册事件
    #register_init(app)

    return app


def register_cors(app: FastAPI) -> None:
    """
    支持跨域
    :param app:
    :return:
    """
    if True:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )


def register_router(app: FastAPI) -> None:
    """
    注册路由
    :param app:
    :return:
    """
    # 项目API
    app.include_router(
        api_v1_router,
    )


def register_init(app: FastAPI) -> None:
    """
    初始化连接
    :param app:
    :return:
    """

    @app.on_event("startup")
    async def init_connect():
        pass
        # 连接redis

    @app.on_event('shutdown')
    async def shutdown_connect():
        """
        关闭
        :return:
        """

        #无任何操作
        pass